/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package reportcenter.admin.ui;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.springframework.binding.value.ValueModel;
import org.springframework.context.ApplicationEvent;
import org.springframework.richclient.application.PageComponentContext;
import org.springframework.richclient.application.event.LifecycleApplicationEvent;
import org.springframework.richclient.application.support.AbstractView;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.ActionCommandExecutor;
import org.springframework.richclient.command.CommandGroup;
import org.springframework.richclient.command.GuardedActionCommandExecutor;
import org.springframework.richclient.command.support.AbstractActionCommandExecutor;
import org.springframework.richclient.command.support.GlobalCommandIds;
import org.springframework.richclient.dialog.ConfirmationDialog;
import org.springframework.richclient.list.ListSelectionValueModelAdapter;
import org.springframework.richclient.list.ListSingleSelectionGuard;
import reportcenter.admin.business.AdminReportDao;
import reportcenter.report.dominio.report.Report;

/**
 *
 * @author renan_luz
 */

public class AdminReportView extends AbstractView {
    
    private AdminReportTable adminReportTable;
    
    private AdminReportDao adminReportDao;
    public AdminReportDao getAdminReportDao() {
        return adminReportDao;
    }

    public void setAdminReportDao(AdminReportDao adminReportDao) {
        this.adminReportDao = adminReportDao;
    }
    
    /**
     * Campo texto que permite filtrar o conteúdo da tabela.
     */
    private JTextField filterField;
    @Override
    protected JComponent createControl() {
        
        //Painel do filtro
        JPanel filterPanel = new JPanel(new BorderLayout());
        //Label do filtro
        JLabel filterLabel = getComponentFactory().createLabel("adminReportFilter.label");
        filterPanel.add(filterLabel, BorderLayout.WEST);

        String tip = getMessage("adminReportFilter.caption");
        filterField = getComponentFactory().createTextField();
        filterField.setToolTipText(tip);
        filterPanel.add(filterField, BorderLayout.CENTER);
        filterPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        //instancia tabela de relatórios
        adminReportTable = new AdminReportTableFactory().createAdminReportTable();
        
        JPanel view = new JPanel(new BorderLayout());
        JScrollPane sp = getComponentFactory().createScrollPane(adminReportTable.getControl());
        view.add(filterPanel, BorderLayout.NORTH);
        view.add(sp, BorderLayout.CENTER);
        
        return view;
    }
    
    /**
     * Prepara a tabela contendo os objetos do relatório. A tabela fornece conjunto de funcionalidades presentes nessa View.
     * Na chamada desse método o método set {@link #setReportTable(ReportTable)} já terá sido invocado como parte do contexto
     * de criação do bean.
     */
    private class AdminReportTableFactory {
        public AdminReportTable createAdminReportTable(){
            AdminReportTable adminReportTable = new AdminReportTable(adminReportDao);
            
            adminReportTable.setDoubleClickHandler(propExecutor);
            
            //Evento de filtro
            EventList baseList = adminReportTable.getBaseEventList();
            TextFilterator filterator = GlazedLists.textFilterator(new String[]{"title","subtitle","query"});
            FilterList filterList = new FilterList(baseList,new TextComponentMatcherEditor(filterField, filterator));
            adminReportTable.setFinalEventList(filterList);
            
            //Configuração do menu de popup
            CommandGroup popup = new CommandGroup();
            popup.add((ActionCommand) getWindowCommandManager().getCommand("propertiesCommand", ActionCommand.class));
            popup.addSeparator();
            popup.add((ActionCommand) getWindowCommandManager().getCommand("deleteCommand", ActionCommand.class));
            adminReportTable.setPopupCommandGroup(popup);
            
            adminReportTable.setStatusBar(getStatusBar());
            
            
            ValueModel selectionHolder = new ListSelectionValueModelAdapter(adminReportTable.getSelectionModel());
            new ListSingleSelectionGuard(selectionHolder, propExecutor);
            new ListSingleSelectionGuard(selectionHolder, delExecutor);
                    
            return adminReportTable;
        }
    }
    
    public void onApplicationEvent(ApplicationEvent e) {
        adminReportTable.onApplicationEvent(e);
    }
    
    
    private ActionCommandExecutor newExecutor = new NewExecutor();
    private class NewExecutor implements ActionCommandExecutor{

        public void execute() {
            new AdminReportPropertiesDialog(getAdminReportDao()).showDialog();
        }
        
    }
    
    private GuardedActionCommandExecutor propExecutor = new PropExecutor();
    private class PropExecutor extends AbstractActionCommandExecutor{
        
        public void execute(){
            new AdminReportPropertiesDialog(adminReportTable.getSelectedReport(), getAdminReportDao()).showDialog();
        }
        
    }
    
    private GuardedActionCommandExecutor delExecutor = new DelExecutor();
    private class DelExecutor extends AbstractActionCommandExecutor{
        
        public void execute(){
            // We know exactly one contact will be selected at this time because
            // of the guards put in place in prepareTable.
            final Report report = adminReportTable.getSelectedReport();
            // Query the user to be sure they want to do this
            String title = getMessage("AdminReportView.confirmDelete.title");
            String message = getMessage("AdminReportView.confirmDelete.message");
            ConfirmationDialog dlg = new ConfirmationDialog(title, message) {

                protected void onConfirm() {
                    // Delete the object from the persistent store.
                    getAdminReportDao().delete(report);
                    // And notify the rest of the application of the change
                    getApplicationContext().publishEvent(
                            new LifecycleApplicationEvent(LifecycleApplicationEvent.DELETED, report));
                }
            };
            dlg.showDialog();
        }
    }
    
    /**
     * Registra os executores de comando com os comandos associados a eles(comandos registrados em "richclient-application-context.xml"). 
     * Esse método é invocado pelo framework para tornar a view(ex: botão deletar) visível.
     */
    protected void registerLocalCommandExecutors(PageComponentContext context) {
        context.register("newCommand", newExecutor);
        context.register(GlobalCommandIds.PROPERTIES, propExecutor);
        context.register(GlobalCommandIds.DELETE, delExecutor);
    }

}
